package org.example.strategy.Impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.example.config.WxParamConfig;
import org.example.constant.AuthConstants;
import org.example.domain.LoginMember;
import org.example.domain.Member;
import org.example.mapper.LoginMemberMapper;
import org.example.model.SecurityUser;
import org.example.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service(AuthConstants.LOGIN_TYPE_MEMBER)
public class MemberLoginStrategy implements LoginStrategy {

    @Autowired
    private WxParamConfig wxParamConfig;

    @Autowired
    private LoginMemberMapper loginMemberMapper;

    @Override
    public UserDetails realLogin(String username) {

        String url = String.format(wxParamConfig.getUrl(), wxParamConfig.getAppid(), wxParamConfig.getSecret(), username);

        String jsonStr = HttpUtil.get(url);

        //判断是否有值
        if (!StringUtils.hasText(jsonStr)) {
            throw new InternalAuthenticationServiceException("登录异常 请重试。。。");
        }
        //将Json格式转换成Json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);

        //获取openid
        String openid = jsonObject.getString("openid");
        //判断是否有值
        if (!StringUtils.hasText(openid)) {
            throw new InternalAuthenticationServiceException("登录异常 请重试。。。");
        }

        //根据会员id查找会员对象
        LoginMember loginMember = loginMemberMapper.selectOne( new LambdaQueryWrapper<LoginMember>()
                .eq( LoginMember::getOpenId, openid)
        );
        //判断会员对象是否存在
        if (ObjectUtil.isNull(loginMember)) {
            //会员不存在 创建会员对象
            loginMember = registerMember(openid);
        }
        //判断会员账号状态是否正常
        if (!loginMember.getStatus().equals(1)) {
            throw new InternalAuthenticationServiceException("账号异常 请联系管理员。。。");
        }
        //账号正常 会员存在 返回SecurityUser对象
        SecurityUser securityUser = new SecurityUser();
        securityUser.setUserId(Long.valueOf(loginMember.getId()));
        securityUser.setLoginType(AuthConstants.LOGIN_TYPE_MEMBER);
        securityUser.setUsername(loginMember.getOpenId());
        securityUser.setStatus(loginMember.getStatus());
        securityUser.setPassword(wxParamConfig.getPwd());
        securityUser.setOpenid(loginMember.getOpenId());

        return securityUser;
    }

    private LoginMember registerMember(String openid) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteAddr();
        LoginMember loginMember = new LoginMember();
        loginMember.setOpenId(openid);
        loginMember.setStatus(1);
        loginMember.setCreateTime(new Date());
        loginMember.setUpdateTime(new Date());
        loginMember.setUserLasttime(new Date());
        loginMember.setUserRegip(ip);
        loginMember.setUserLastip(ip);
        loginMember.setScore(0);

        loginMemberMapper.insert(loginMember);
        return loginMember;

    }

//    public static void main(String[] args) {
//        System.out.println(new BCryptPasswordEncoder().encode("WECHAT"));
//
//    }

}
